<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/1/16
 * Time: 11:24
 */

namespace app\teacher\controller;


use app\common\model\SpecialColumn;
use app\teacher\lib\ApiResponse;
use app\teacher\lib\TeacherBaseController;
use think\Request;

class Column extends TeacherBaseController
{
    public function statuses() {
        return ApiResponse::success(SpecialColumn::getStatusNames());
    }

    public function names(string $keywords = null) {
        $list = SpecialColumn::simpleList($this->teacherId, $keywords);
        return ApiResponse::success($list);
    }

    public function list(string $keywords = null, Request $request) {
        $status = $request->param('status');
        if (is_null($status) || ''===$status) {
            $status = -1;
        } else {
            $status = intval($status);
        }
        $result = SpecialColumn::manageList($this->limit,$this->offset,$this->teacherId,$status,$keywords);
        return $result;
    }

    public function save() {
        $data = $this->validFormData([
            ['column_title', 'require',],
            ['column_detail', 'require',],
            ['column_id', 'integer',],
            ['column_cover', 'url',],
            ['column_sales', 'integer',],
            ['column_status', 'integer',],
            ['column_expiry', 'integer',],
        ]);

        if (isset($data['column_id'])) {
            $model = SpecialColumn::get($data['column_id']);
        }
        if (empty($model)) {
            $model = new SpecialColumn();
        }

        $model->data($data);
        $model->column_teacher = $this->teacherId;
        if (isset($model->column_id)) {
            $model->column_updatetime = time();
        } else {
            $model->column_updatetime = $model->column_createtime = time();
        }

        $model->save();

        return ApiResponse::success();
    }

    public function status() {
        $form = $this->validFormData([
            ['id', 'require|integer',],
            ['status', 'require|^[0-2]$',],
        ]);

        $re = SpecialColumn::setStatus($form['id'], $form['status']);
        if ($re) return ApiResponse::success();
        else return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED);
    }
}